<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../public/js/ffmpeg.min.js"></script>
    <script>
        function readFileAsArrayBuffer(file) {
            return new Promise((resolve, reject) => {
                let fileredr = new FileReader();
                fileredr.onload = () => resolve(fileredr.result);
                fileredr.onerror = () => reject(fileredr);
                fileredr.readAsArrayBuffer(file);
            });
        }

        // Converts Uint8Array to Base64
        function convertBitArrtoB64(bitArr) { 
            return btoa(bitArr.reduce((data, byte) => data + String.fromCharCode(byte), ''));
        }

        const outputFileExt = '.mp3';
        const uploadMedia = document.getElementById('uploadMedia');

        uploadMedia.addEventListener('change', async(evt)=> {
        const file=evt.target.files[0];
        const fileName=file.name;
        let arrBuffer = await readFileAsArrayBuffer(file);
        let uInt8Array = new Uint8Array(arrBuffer);
        
        // Note that these filepaths must be relative to where the
        // other 3 files are placed
        const ffmpeg = FFmpeg.createFFmpeg({
            corePath: new URL('../public/js/ffmpeg/ffmpeg-core.js', document.location).href,
            workerPath: new URL('../public/js/ffmpeg/ffmpeg-core.worker.js', document.location).href,
            wasmPath: new URL('../public/js/ffmpeg/ffmpeg-core.wasm', document.location).href,
            log: true
        });
        await ffmpeg.load();
        
        ffmpeg.FS('writeFile', fileName, uInt8Array);
        await ffmpeg.run('-i', fileName, `output${outputFileExt}`);

        let data = ffmpeg.FS('readFile', `output${outputFileExt}`); // Uint8Array
        let b64Str = convertBitArrtoB64(data);
        const encodedData=`data:audio/${outputFileExt};base64,${b64Str}`;

        // to download the output processed audio file
        const dwnLink = document.createElement('a');
        dwnLink.download = `output${outputFileExt}`;
        dwnLink.href= encodedData;
        dwnLink.click();
        });
    </script>
</head>
<body>
    <input id='uploadMedia' type='file' accept='audio/*' />
</body>
</html>